package cn.ren.service;

import cn.ren.constant.RedisConstant;
import cn.ren.dao.SetMealDao;
import cn.ren.entity.PageResult;
import cn.ren.entity.Result;
import cn.ren.pojo.Setmeal;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: itcast_health
 * @description:
 * @author: ren
 * @create: 2020-02-25 17:16
 **/

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;
    @Autowired //注入jedis连接池
    private JedisPool jedisPool;
    //注入freeMarker配置对象
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    //注入配置文件属性值,通过sptingEL来表示
    @Value("${out_put_path}")
    private String outputpath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        //将文件名存到redis保存有用数据的set里
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //对勾选的检查组数据进行空值判断
        if(checkgroupIds != null && checkgroupIds.length > 0){
            setMealAndCheckGroup(setmeal.getId(),checkgroupIds);
        }

        //新增套餐后，需要生成静态页面
        generateMobileStaticHtml();
    }
    //生成静态页面
    public void generateMobileStaticHtml(){
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    /**
     * 生成套餐列表页面
     * @param setmealList
     * @throws Exception
     */
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String,Object> map = new HashMap<>();
        map.put("setmealList",setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    /**
     * 生成套餐详情页面
     * @param setmealList
     */
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        //遍历获取每个套餐的详细信息
        for (Setmeal setmeal : setmealList) {
            Setmeal setmealDetail = this.findById(setmeal.getId());
            //根据这个套餐的详细信息，生成该id的静态页面
            Map<String,Object> map = new HashMap<>();
            map.put("setmeal",setmealDetail);
            this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    /**
     * 生产静态页面的通用方法
     * @param templateName
     * @param htmlPageName
     * @param dataMap
     */
    public void generateHtml(String templateName,String htmlPageName,Map<String,Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File docFile = new File(outputpath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new
                    FileOutputStream(docFile)));
            // 输出文件
            template.process(dataMap,out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }





    @Override
    public PageResult queryPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setMealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setMealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findOrderCountGroupBySetmeal() {
        return setMealDao.findOrderCountGroupBySetmeal();
    }

    public void setMealAndCheckGroup(Integer mealId,Integer[] checkGroupIds){
        for (Integer groupId : checkGroupIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("setmeal_id",mealId);
            map.put("checkgroup_id",groupId);
            setMealDao.setMealAndCheckGroup(map);
        }
    }
}
